package com.like.lazyfragment.ui3

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import com.like.lazyfragment.R
import kotlinx.android.synthetic.main.activity_main3.view.*

abstract class LazyFragment : Fragment() {
    private var mContext: Context? = null
    private var isFirstLoad = true // 是否第一次加载
    private var findViewById: TextView? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mContext = activity
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = LayoutInflater.from(mContext).inflate(contentViewId, null)
        initView(view)
        return view
    }

    override fun onResume() {
        super.onResume()
//        if (isFirstLoad) { // 将数据加载逻辑放到onResume()方法中
            initData()
            initEvent()
            isFirstLoad = false
//        }
    }

    override fun onPause() {
        super.onPause()
        findViewById?.text = "loading..loading..."
    }
    /**
     * 设置布局资源id
     *
     * @return
     */
    protected abstract val contentViewId: Int

    /**
     * 初始化视图
     *
     * @param view
     */
    protected fun initView(view: View?) {
        findViewById = view?.findViewById<TextView>(R.id.textView)
    }

    override fun getLifecycle(): Lifecycle {
        return super.getLifecycle()
    }
    /**
     * 初始化数据
     */
    protected fun initData() {
        findViewById?.text = getString()
    }

    /**
     * 初始化事件
     */
    protected fun initEvent() {}

    abstract fun getString(): String
}